package me.chan.netty.basic;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class Server {

    public static void main(String[] args) {

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(new NioEventLoopGroup())
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws IOException {
                            ch.pipeline().addLast(new StringDecoder())
                                            .addLast(new SimpleChannelInboundHandler<String>() {
                                                @Override
                                                protected void channelRead0(ChannelHandlerContext ctx, String msg) throws IOException {
                                                    log.info("server report: receive 【{}】 from client", msg);
                                                }
                                            });
                        }
                    }).bind(8080);
    }
}
